package cn.hh.basic.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;

import java.io.IOException;

/**
 *  短信发送工具类
 */
public class SmsUtil {

    //用户名
    public static final String UID = "h744430983";
    //秘钥
    public static final String KEY = "ED71A049DF58270BA70B48A7CF17EBA5";

    /**
     * 发送短信
     *
     * @param phones  手机们 a,b
     * @param content 发送内容
     * @return 返回值
     */
    public static String sendSms(String phones, String content) { // 两个参数, 1.手机号  2.短信内容
        PostMethod post = null;
        try {
            HttpClient client = new HttpClient();
            post = new PostMethod("http://utf8.api.smschinese.cn");
            post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
            NameValuePair[] data = {new NameValuePair("Uid", SmsUtil.UID),
                    new NameValuePair("Key", SmsUtil.KEY),
                    new NameValuePair("smsMob", phones), // 手机号
                    new NameValuePair("smsText", content)}; // 发送的内容
            post.setRequestBody(data);

            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:" + statusCode); // HTTP状态码:200 404 400
            for (Header h : headers) {
                System.out.println(h.toString());
            }
            String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
            return result;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

}

